//专门用来存放关于文章的所有接口
const Router = require('koa-router'); //引入路由
const essay = new Router();
const db = require('../utils/db');
//写对应的接口

//get文章
essay.get('/',async ctx=>{
    let data = await new Promise((reslove,reject) => {
        return db.query(`select * from essay_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
            })
        })
        const totalCount = data.length;
        console.log(totalCount);
        ctx.body = {
            totalCount,
            data
        }
    })

//插入文章
essay.post('/insert', async ctx => {

    let searchSql0 = `select MAX(id) from essay_class`;
    let idresult = await new Promise((resolve, reject) => {
        return db.query(searchSql0,(err,data)=>{
            if(err) throw err
            resolve(data[0])
        })
    }) 

    const data = ctx.request.body
    console.log(data);
    let searchSql = `insert into essay_class (id,essay_title,essay_txt,essay_img) values ("${++idresult['MAX(id)']}","${data.essay_title}","${data.essay_txt}","${data.essay_img}")`
    
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })//插入新数据
    let result0 = await new Promise((reslove,reject) => {
        return db.query(`select * from essay_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
        })
    })
    //返回所有数据
    ctx.body = result0;
})


//编辑时根据id获取数据
essay.get('/:id',async ctx=>{
    const {id} = ctx.request.params;
    let searchSql = `select * from essay_class where id="${id}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql,(err,data)=>{
            if(err) throw err
            resolve(data)
        })
    })
    ctx.body = result;
})

//修改文章
essay.put('/:id',async ctx=>{
    const {id} = ctx.request.params;
    const data = ctx.request.body;
    let searchSql = `update essay_class set essay_title="${data.essay_title}", essay_txt="${data.essay_txt}",essay_img="${data.essay_img}" where id="${id}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql,(err,data)=>{
            if(err) throw err
            resolve(data)
        })
    })
    ctx.body = result
})

//删除文章    
essay.post('/delete/:id',async ctx=>{
    const {id} = ctx.request.params
    let searchSql = `delete from essay_class where id="${id}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })//删除数据
    let result0 = await new Promise((reslove,reject) => {
        return db.query(`select * from essay_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
        })
    })
    //返回所有数据
    ctx.body = result0;
})


module.exports = essay;